const PREFIX = 'smartAi-';

const local = window.localStorage;

function format(value: any) {
  return value === undefined || value === null ? '' : value;
}

function parseLocal(data: any) {
  try {
    return JSON.stringify({
      value: format(data),
    });
  } catch (e) {
    console.log('JSON.stringify ERR', e);
  }
  return null;
}

function parseResult(data: string) {
  if (data == null) {
    return null;
  }
  try {
    const result = JSON.parse(data);
    return result.value;
  } catch (e) {
    console.log('JSON.parse ERR', e);
  }
}

// localStore操作类
class LocalData {
  clear(): void {
    local.clear();
  }

  del(key: string): void {
    local.removeItem(PREFIX + key);
  }

  get(key: string): any {
    return parseResult(local[PREFIX + key]);
  }

  set(key: string, value: any): void {
    try {
      const data = parseLocal(value);
      if (data != null) {
        local.setItem(PREFIX + key, data);
      }
    } catch (e) {
      console.error(e);
    }
  }
}

export default new LocalData();
